/**
 * 
 */
package org.auth.service;

import org.apache.commons.lang3.StringUtils;
import org.auth.cache.VerificationCodeCache;
import org.auth.cache.bean.CacheObjectBean;
import org.auth.cache.bean.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 验证码相关
 *
 * @author ying12.ma@nttdata.com
 */
@Service
public class BaseVerificationCodeServiceImpl implements BaseVerificationCodeService {
	
	/**
	 * 缓存
	 */
	@Autowired
	private VerificationCodeCache cache;

	/**
	 * 生成验证码
	 * 
	 * @param telphone 手机号
	 * @param clientName 客户端类型
	 * @return 验证码
	 */
	@Override
	public VerificationCode getVerificationCode(String telphone, String clientName) {
		return cache.getVerificationCode(cache.getCacheCode(telphone, clientName), null);
	}
	
	/**
	 * 生成验证码
	 * 
	 * @param telphone 手机号
	 * @param clientName 客户端类型
	 * @param check check
	 * @return 验证码
	 */
	@Override
	public VerificationCode getVerificationCode(String telphone, String clientName, CacheObjectBean check) {
		return cache.getVerificationCode(cache.getCacheCode(telphone, clientName), check);
	}
	
	/**
	 * 更新验证码
	 * 
	 * @param telphone 手机号
	 * @param clientName 客户端类型
	 * @param verificationCode 验证码
	 * @return 验证码
	 */
	@Override
	public VerificationCode updateLastSendDate(String telphone, String clientName, VerificationCode verificationCode) {
		return cache.updateLastSendDate(cache.getCacheCode(telphone, clientName),verificationCode);
	}

	/**
	 * 检测验证码
	 * 
	 * @param telphone 手机号
	 * @param clientName 客户端类型
	 * @param verificationCode 验证码
	 * @return 验证结果
	 */
	@Override
	public boolean chkVerificationCode(String telphone, String clientName, String verificationCode) {
		VerificationCode savedVerificationCode = cache.getVerificationCode(cache.getCacheCode(telphone, clientName), null);
		if(StringUtils.equals(savedVerificationCode.getVerificationCode(), verificationCode)) {
			cache.delVerificationCode(cache.getCacheCode(telphone, clientName));
			return true;
		}
		return false;
	}
	
	/**
	 * 删除验证码
	 * 
	 * @param telphone 手机号
	 * @param clientName 客户端类型
	 */
	public void delVerificationCode(String telphone, String clientName) {
		cache.delVerificationCode(cache.getCacheCode(telphone, clientName));
	}

}
